package com.lh.gateway.filter;

import com.lh.auth.utils.CookieUtils;
import com.lh.auth.utils.JwtUtils;
import com.lh.gateway.config.FilterProperties;
import com.lh.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liuhe
 * @date 2020/07/07
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class LoginFilter extends ZuulFilter {

    private final JwtProperties jwtProperties;
    private final FilterProperties filterProperties;

    public LoginFilter(JwtProperties jwtProperties, FilterProperties filterProperties) {
        this.jwtProperties = jwtProperties;
        this.filterProperties = filterProperties;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();
        log.debug("requestUrl:{}", requestURI);
        // 判断白名单，遍历允许访问的路径
        for (String path : this.filterProperties.getAllowPaths()) {
            if (requestURI.startsWith(path)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = currentContext.getRequest();
        String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
        try {
            // 校验token
            JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
            // 校验异常
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
        }
        return null;
    }
}
